//
//  DecorateOrdersCenterViewController.m
//  customer
//
//  Created by Holothurian on 2018/11/6.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "DecorateOrdersCenterViewController.h"
#import "SelfInfoLabelTableViewCell.h"
#import "AppointOrderDetailViewController.h"
#import "DecorateOrdersCenterFooterView.h"

static NSString *OrdersCenterCellIdentifier =  @"OrdersCenterCellIdentifier";
static NSString *OrdersCenterFooterID = @"OrdersCenterFooterID";
@interface DecorateOrdersCenterViewController ()<UITableViewDelegate,UITableViewDataSource,OrdersCenterFooterDelegate>

@property (nonatomic,strong)NSArray *keyArray;

@property (nonatomic,strong)NSMutableArray *valueArray;



@end

@implementation DecorateOrdersCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createMainView];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

- (void)createMainView{
    if (self.selectIndex == 0) {
        self.keyArray = @[@"下单时间",@"选择类型",@"联系人",@"联系电话",@"详细地址"];
        self.title = @"装修订单";
    }else{
        self.keyArray = @[@"下单时间",@"项目名称",@"联系人",@"联系电话",@"详细地址"];
        self.title = @"加配订单";
    }
   AutoWeakSelf
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(NAVIGATION_BAR_HEIGHT);
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_offset(F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(0));
    }];
    [self setRefreshEnabled:YES];
    [self.tableView registerClass:[SelfInfoLabelTableViewCell class] forCellReuseIdentifier:OrdersCenterCellIdentifier];
    [self.tableView registerClass:[DecorateOrdersCenterFooterView class] forHeaderFooterViewReuseIdentifier:OrdersCenterFooterID];
}

- (void)loadDataList{
    AutoWeakSelf
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserID)] forKey:@"member_id"];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)] forKey:@"member_token"];
    [dict setObject:[NSNumber numberWithInteger:self.page] forKey:@"page"];
    
    if (self.selectIndex == 0) {
        // 1:已预约  2:已确认 3:已支付订单  4:已支付进度款 5:已支付尾款 6:结束
        [dict setObject:@"1,2" forKey:@"order_type"];//1:装修预约 2:设计预约
        [dict setObject:@"2,3,4,5" forKey:@"order_state"];//1:已预约
    }else if (self.selectIndex == 1){
        //1:已预约  2:已确认 3:已支付定金   4:已支付尾款 5:结束
        [dict setObject:@"2,3,4" forKey:@"order_state"];//1:已预约
    }
    if (self.page == 1) {
        [self.valueArray removeAllObjects];
        [self.dataList removeAllObjects];
    }
    [self showLoading];
    [[QYNetManager sharedManager]POST:(self.selectIndex == 1 ? kGetCustomizedOrders:kGetRenovationOrders) parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        [weakSelf endReresh];
        id resultData = responseObject[@"data"];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if (![resultData isKindOfClass:[NSNull class]] && [resultData isKindOfClass:[NSArray class]] && [resultData count]){
            if ([responseObject[@"total"] integerValue]<10 || ([responseObject[@"total"] integerValue] == self.dataList.count)) {
                [weakSelf.tableView.mj_footer removeFromSuperview];
            }
            for (NSDictionary *dict in resultData) {
                NSMutableArray *tempArr = [NSMutableArray array];
                if (self.selectIndex == 0) {
                    DecorateInsertOrderModel *model = [DecorateInsertOrderModel yy_modelWithDictionary:dict];
                    [tempArr addObject:model.create_time];
                    [tempArr addObject:model.style_name];
                    [tempArr addObject:model.contact_name];
                    [tempArr addObject:model.contact_mobile];
                    [tempArr addObject:model.address_detail];
                    [weakSelf.dataList addObject:model];
                }else{
                    CustomAddModel *model = [CustomAddModel yy_modelWithDictionary:dict];
                    [tempArr addObject:model.create_time];
                    [tempArr addObject:model.customized_name];
                    [tempArr addObject:model.contact_name];
                    [tempArr addObject:model.contact_mobile];
                    [tempArr addObject:model.address_detail];
                    [weakSelf.dataList addObject:model];
                }
                [weakSelf.valueArray addObject:tempArr];
            }
            [weakSelf.tableView reloadData];
            weakSelf.tableView.showEmpty = NO;
        }else if (![resultData isKindOfClass:[NSNull class]] && [resultData isKindOfClass:[NSArray class]] && [resultData count] == 0){
            [weakSelf.dataList removeAllObjects];
            weakSelf.tableView.showEmpty = YES;
            [weakSelf.tableView reloadData];
        }
    } Failure:^(NSError *error) {
        [weakSelf endReresh];
        [weakSelf hideLoading];
        weakSelf.tableView.showEmpty = YES;
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

/**
 立即支付
 order_id
 */
- (void)payMaintailOrderWithURL:(NSString *)urlString OrderId:(NSString *)orderId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:orderId?:@"" forKey:@"order_id"];
    [dict setObject:@"wx" forKey:@"pay_way"];
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:urlString parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                PayOrderModel *payModel = [PayOrderModel yy_modelWithDictionary:responseObject[@"data"]];
                __block typeof(weakSelf) strongSelf = weakSelf;
                [PayStyleUtil doWxpay:payModel payDone:^(NSString * _Nonnull errorMsg) {
                    if (!errorMsg) {
                        [strongSelf showTipWithTitle:@"支付成功"];
                        [strongSelf loadDataList];
                    }else{
                        [strongSelf showErrorTipWithTitle:errorMsg];
                    }
                }];
            }else{
                [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
            }
        }else{
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.valueArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [(NSMutableArray *)self.valueArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //懒得再写一个cell
    SelfInfoLabelTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:OrdersCenterCellIdentifier];
    cell.nameLabel.text = self.keyArray[indexPath.row];
    cell.nameLabel.textColor = [HSPublic colorWithHexString:@"333333"];
    cell.detailNameLabel.textColor = [HSPublic colorWithHexString:@"333333"];
    NSString *valueString = self.valueArray[indexPath.section][indexPath.row]?:@"";
    cell.detailNameLabel.text = valueString;
    cell.detailNameLabel.textAlignment = NSTextAlignmentLeft;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 10)];
    backView.backgroundColor = [UIColor appColor];
    return backView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    DecorateOrdersCenterFooterView *backView = [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:OrdersCenterFooterID];
    backView.delegate = self;
    if (self.selectIndex == 0) {
        DecorateInsertOrderModel *model = self.dataList[section];
        backView.section = section;
        backView.orderType = self.selectIndex;
        backView.orderState = [model.order_state integerValue];
    }else{
        CustomAddModel *model = self.dataList[section];
        backView.section = section;
        backView.orderType = self.selectIndex;
        backView.orderState = [model.order_state integerValue];
    }
    return backView;
}

#pragma mark - OrdersCenterFooterDelegate
- (void)ordersCenterFooterCurrentOrderLookUpSection:(NSInteger)section{
    AppointOrderDetailViewController *orderDetail = [AppointOrderDetailViewController new];
    switch (self.selectIndex) {
        case 0:{
            DecorateInsertOrderModel *model = self.dataList[section];
            orderDetail.order_id = model.order_id;
        }break;
        case 1:{
            CustomAddModel *model = self.dataList[section];
            orderDetail.order_id = model.order_id;
        }
        default:
            break;
    }
    orderDetail.selectIndex = self.selectIndex + 3;
    TAB_PUSH(self, orderDetail, YES);
}


/**
 装修订单/加配订单 支付定金、支付尾款等操作

 @param section 当前分组
 */
- (void)ordersCenterFooterOrderActionSection:(NSInteger)section{
    switch (self.selectIndex) {
        case 0:{//装修订单
            /**
            1:已预约  2:已确认 3:已支付订单  4:已支付进度款 5:已支付尾款 6:结束
            */
            DecorateInsertOrderModel *decorateModel = self.dataList[section];
            //下一个状态 该支付了
            if ([decorateModel.order_state integerValue] == 2 || [decorateModel.order_state integerValue] == 3 || [decorateModel.order_state integerValue] == 4) {
                [self payMaintailOrderWithURL:kPayRenovationOrder OrderId:decorateModel.order_id];
            }
        }break;
        case 1:{//加配订单
            //1:已预约  2:已确认 3:已支付定金   4:已支付尾款 5:结束
            CustomAddModel *addModel = self.dataList[section];
            if ([addModel.order_state integerValue] == 2 || [addModel.order_state integerValue] == 3) {
                [self payMaintailOrderWithURL:kPayCustomizedOrder OrderId:addModel.order_id];
            }
        }break;
        default: break;
    }
}

- (NSArray *)keyArray{
    if (!_keyArray) {
        _keyArray = [NSArray array];
    }
    return _keyArray;
}

- (NSMutableArray *)valueArray{
    if (!_valueArray) {
        _valueArray = [NSMutableArray array];
    }
    return _valueArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
